import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
  const config = loadEnv(mode, process.cwd())
  return {
    base: '/react-admin-template/',
    plugins: [
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]'
      })
    ],
    resolve: {
      alias: { // Configure aliases
        '@': path.resolve('src')
      }
    },
    server: {
      proxy: {
        '/api': {
          target: config.VITE_BASIC_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
        '/ws': {
          target: 'ws://localhost:3000',
          ws: true,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/ws/, '')
        }
      }
    },
    esbuild: {
      loader: 'jsx',
      include: /src\/.*\.jsx?$/,
      // include: /src\/.*\.[tj]sx?$/,
      exclude: []
    },
    optimizeDeps: {
      esbuildOptions: {
        loader: { '.js': 'jsx' }, //*********** Add this line
        plugins: [
          {
            name: 'load-js-files-as-jsx',
            setup (build) {
              build.onLoad({ filter: /src\/.*\.js$/ }, async (args) => ({
                loader: 'jsx',
                contents: await fs.readFile(args.path, 'utf8')
              }))
            }
          }
        ]
      }
    },
    extensions: ['.js', '.jsx', '.json', '.png']
  }
})